package com.lp.rpc.server;

import com.lp.rpc.constants.LpConstant;
import com.lp.rpc.domain.LpMessage;
import com.lp.rpc.domain.LpRequest;
import com.lp.rpc.domain.result.LpResult;
import com.lp.rpc.exception.HandlerException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * netty服务端handler
 *
 * @author steakLiu
 */
public class LpServerHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(LpServerHandler.class);

    private static final int readerIndex = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg == null){
            throw new HandlerException("object is null");
        }
        LpRequest lpRequest = (LpRequest) msg;
        Object result = LpServerCall.serviceCall(lpRequest);
        LpResult lpResult = LpResult.success(result);
        LpMessage lpMessage = new LpMessage();
        lpMessage.setMessageType(LpConstant.LpRpcMsgResponse);
        lpMessage.setData(lpResult);
        ctx.writeAndFlush(lpMessage);
    }

    /**
     * netty心跳检测
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("发送心跳");
        if (evt instanceof IdleStateEvent){
            IdleState idleState = ((IdleStateEvent) evt).state();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
